<template>
  <div class="chat-container">
    <div v-for="(message, index) in messages" :key="index" 
         :class="['message-wrapper', message.role === 'user' ? 'user-message' : 'bot-message']">
      <div class="avatar" :class="message.role === 'bot' ? message.avatarClass : ''">
        {{ message.role === 'user' ? '🈴' : message.emoji }}
      </div>
      <div :class="['message-bubble', message.role === 'user' ? 'user-bubble' : 'bot-bubble']">
        <div v-if="message.role === 'bot'" class="markdown-content" v-html="formatMarkdown(message.content)"></div>
        <div v-else>{{ message.content }}</div>
      </div>
    </div>
    <div v-if="loading" class="message-wrapper bot-message">
      <div class="avatar" :class="assistantAvatarClass">
        {{ getAssistantEmoji() }}
      </div>
      <div class="message-bubble bot-bubble typing-indicator">
        <span></span>
        <span></span>
        <span></span>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { marked } from 'marked';

export default {
  name: 'ChatBox',
  data() {
    return {
      messages: [
        {
          role: 'bot',
          content: '你好！我是AI助手，请问有什么可以帮助你的？',
          avatarClass: 'general-avatar',
          emoji: '🤖',
          task: 'general_assistant'
        }
      ],
      sessionId: 'user-' + Date.now(), // Generate a unique session ID
      loading: false,
      selectedTask: 'general_assistant', // Default task
      selectedModel: 'gpt-3.5-turbo' // Default model
    }
  },
  computed: {
    assistantAvatarClass() {
      switch(this.selectedTask) {
        case 'code_helper':
          return 'code-avatar';
        case 'product_manager':
          return 'product-avatar';
        default:
          return 'general-avatar';
      }
    }
  },
  methods: {
    async receiveMessage(message) {
      if (!message.trim()) return;
      
      // Add user message
      this.messages.push({
        role: 'user',
        content: message
      });
      
      // Show loading indicator
      this.loading = true;
      
      try {
        // Call the backend API
        const response = await axios.post('/chat', {
          session_id: this.sessionId,
          user_input: message,
          task: this.selectedTask,
          model: this.selectedModel
        });
        
        // Add bot response with current assistant type
        this.messages.push({
          role: 'bot',
          content: response.data.reply,
          avatarClass: this.assistantAvatarClass,
          emoji: this.getAssistantEmoji(),
          task: this.selectedTask
        });
      } catch (error) {
        console.error('API Error:', error);
        // Show error message
        this.messages.push({
          role: 'bot',
          content: '抱歉，我现在无法回应。请稍后再试。',
          avatarClass: this.assistantAvatarClass,
          emoji: this.getAssistantEmoji(),
          task: this.selectedTask
        });
      } finally {
        // Hide loading indicator
        this.loading = false;
        
        // Scroll to bottom
        this.$nextTick(() => {
          const container = document.querySelector('.chat-main');
          if (container) {
            container.scrollTop = container.scrollHeight;
          }
        });
      }
    },
    
    // Method to change the assistant type
    changeAssistantType(task) {
      this.selectedTask = task;
      // Inform the user about the change
      this.messages.push({
        role: 'bot',
        content: `我现在切换到${task === 'code_helper' ? '编程助手' : task === 'product_manager' ? '产品经理助手' : '一般助手'}模式。`,
        avatarClass: this.assistantAvatarClass,
        emoji: this.getAssistantEmoji(),
        task: task
      });
    },
    
    // Method to change the model
    changeModel(model) {
      this.selectedModel = model;
      this.messages.push({
        role: 'bot',
        content: `模型已切换到 ${model}。`,
        avatarClass: this.assistantAvatarClass,
        emoji: this.getAssistantEmoji(),
        task: this.selectedTask
      });
    },
    
    // Format markdown content
    formatMarkdown(text) {
      try {
        return marked(text);
      } catch (error) {
        console.error('Markdown parsing error:', error);
        return text;
      }
    },
    
    // Get assistant emoji based on selected task
    getAssistantEmoji() {
      switch(this.selectedTask) {
        case 'code_helper':
          return '👨‍💻';
        case 'product_manager':
          return '📊';
        default:
          return '🤖';
      }
    }
  }
}
</script>

<style>
/* Add markdown styling */
.markdown-content {
  font-family: var(--font-main);
  line-height: 1.6;
}

.markdown-content h1, 
.markdown-content h2, 
.markdown-content h3,
.markdown-content h4,
.markdown-content h5,
.markdown-content h6 {
  margin-top: 1rem;
  margin-bottom: 0.5rem;
  font-weight: 600;
}

.markdown-content h1 { font-size: 1.4rem; }
.markdown-content h2 { font-size: 1.3rem; }
.markdown-content h3 { font-size: 1.2rem; }
.markdown-content h4 { font-size: 1.1rem; }
.markdown-content h5 { font-size: 1rem; }
.markdown-content h6 { font-size: 0.9rem; }

.markdown-content p {
  margin-bottom: 0.75rem;
}

.markdown-content ul, 
.markdown-content ol {
  margin-bottom: 0.75rem;
  padding-left: 1.5rem;
}

.markdown-content li {
  margin-bottom: 0.25rem;
}

.markdown-content code {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 0.2rem 0.4rem;
  border-radius: 3px;
  font-family: monospace;
  font-size: 0.9em;
}

.markdown-content pre {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 0.75rem;
  border-radius: 5px;
  overflow-x: auto;
  margin-bottom: 0.75rem;
}

.markdown-content pre code {
  background-color: transparent;
  padding: 0;
  font-size: 0.85em;
  line-height: 1.45;
}

.markdown-content blockquote {
  border-left: 4px solid #ddd;
  padding-left: 1rem;
  margin-left: 0;
  margin-bottom: 0.75rem;
  color: #666;
}

.markdown-content table {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 0.75rem;
}

.markdown-content table th,
.markdown-content table td {
  border: 1px solid #ddd;
  padding: 0.5rem;
  text-align: left;
}

.markdown-content table th {
  background-color: rgba(0, 0, 0, 0.05);
}
</style>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  padding-bottom: 0.5rem;
}

.message-wrapper {
  display: flex;
  gap: 0.75rem;
  max-width: 80%;
}

.user-message {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.bot-message {
  align-self: flex-start;
}

.avatar {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 50%;
  background-color: #f3f4f6;
  font-size: 1.25rem;
}

.user-message .avatar {
  background-color: #e6edff;
}

.general-avatar {
  background-color: #4a6cf7;
  color: white;
}

.code-avatar {
  background-color: #2dce89;
  color: white;
}

.product-avatar {
  background-color: #fb6340;
  color: white;
}

.message-bubble {
  padding: 0.75rem 1rem;
  border-radius: 1rem;
  font-size: 0.9375rem;
  max-width: calc(100% - 3.25rem);
  word-break: break-word;
}

.user-bubble {
  background-color: var(--color-user);
  color: white;
  border-bottom-right-radius: 0.25rem;
}

.bot-bubble {
  background-color: var(--color-bot);
  color: var(--color-text);
  border-bottom-left-radius: 0.25rem;
}

/* Typing indicator */
.typing-indicator {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  min-width: 3.5rem;
  min-height: 1.5rem;
}

.typing-indicator span {
  display: inline-block;
  width: 0.5rem;
  height: 0.5rem;
  background-color: var(--color-text-light);
  border-radius: 50%;
  animation: bounce 1.4s infinite ease-in-out both;
}

.typing-indicator span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes bounce {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}
</style>